package pattern.Composite;

import java.util.ArrayList;

/**
 * Created by Asin Liu on 2017/5/10.
 */
public interface IFilter {

    boolean match(String word);
}


// 树叶型过滤器，过滤单词中长度大于指定长度
class LengthFilter implements IFilter {
    private int length;

    public LengthFilter(int length) {
        this.length = length;
    }

    @Override
    public boolean match(String word) {
        if (word.length() > length) {
            return true;
        }
        return false;
    }
}

// 树叶型过滤器，过滤单词中包含有某个字符字串
class ContainsFilter implements IFilter {
    private String subStr;

    public ContainsFilter(String subStr) {
        this.subStr = subStr;
    }

    @Override
    public boolean match(String word) {
        if (word.contains(subStr)) {
            return true;
        }
        return false;
    }
}


// 树叶型过滤器，过滤单词中以某个字符字串结束
class EndFilter implements IFilter {
    private String subStr;

    public EndFilter(String subStr) {
        this.subStr = subStr;
    }

    @Override
    public boolean match(String word) {
        if (word.endsWith(subStr)) {
            return true;
        }
        return false;
    }
}

// 抽象组合型过滤器，类似于树枝节点
abstract class CompositeFilter implements IFilter {

    protected ArrayList<IFilter> filters;

    public CompositeFilter() {
        this.filters = new ArrayList<IFilter>();
    }

    // 继续将 IFilter 接口中的 match() 声明为 abstract，
    // 由具体的过滤器子类进行实现
    public abstract boolean match(String word);

    // 添加过滤器链
    public void addFilters(ArrayList<IFilter> filters) {
        this.filters.addAll(filters);
    }

    // 添加一个过滤器
    public void addFilter(IFilter filter) {
        this.filters.add(filter);
    }

    // 既然是树枝过滤器，其下必有子过滤器
    public ArrayList<IFilter> getFilters() {
        return this.filters;
    }
}


// and 过滤器，树枝型过滤器
class AndFilter extends CompositeFilter {
    @Override
    public boolean match(String word) {
        for (IFilter filter : super.filters) {
            if (!(filter.match(word))) {
                return false;
            }
        }
        return true;
    }
}


// or 过滤器，树枝型过滤器
class OrFilter extends CompositeFilter {
    @Override
    public boolean match(String word) {
        for (IFilter filter : super.filters) {
            if (filter.match(word)) {
                return true;
            }
        }
        return false;
    }
}